package com.me.demotable;


import com.car.mgr.web.qdsl.utils.RestResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;


@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理 @valid 参数约束异常
     * @param ex 异常
     * @return 异常信息
     */
    @ExceptionHandler({ MethodArgumentNotValidException.class })
    public ResponseEntity<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(RestResult.result(HttpStatus.BAD_REQUEST,
                ex.getBindingResult().getFieldErrors().stream().map(f -> f.getField() + " : " + f.getDefaultMessage())));
    }

    // 注意，必须 @EnableWebMvc 并且设置  spring.mvc.throw-exception-if-no-handler-found=true
    @ExceptionHandler({ NoHandlerFoundException.class })
    public ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(RestResult.result(HttpStatus.NOT_FOUND, ex.getLocalizedMessage()));
    }

    /**
     * 处理通用异常
     * @param ex 异常
     * @return 异常信息
     */
    @ExceptionHandler({ Exception.class })
    public ResponseEntity<Object> handleAll(Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(RestResult.result(HttpStatus.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage()));
    }
}

